# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：batch_video.py
#日期：2019-10-26
#备注：通过ffmpeg库处理视频信息处理实际遇到的问题
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import os
from pycacho.cachobase.file_rename import rename_num_files,copy_rename_files
from pycacho.cachobase.files_select import get_files,get_all_files
from pythonlession.recordmodule.ffmpeg_model import get_info,get_image
import threading
import time
import math
from pycacho.cachobase.logger import Logger

logger = Logger("batch_video").get_log()

# 原视频：F:\\image\\     输出视频：F:\image\\other\\
def scale_info(size,output_path):
    scale = []
    info = get_files('F:\\image\\','mp4')
    for file in info:
        file_name = os.path.basename(file)
        output_file = output_path + file_name
        #exec_scale = 'ffmpeg -i ' + file +' -y -b:v 1500k -bufsize 1500k -maxrate 1800k -strict -2 -s ' + size + ' '+ output_file
        #exec_scale = 'ffmpeg -i ' + file + ' -y  -strict -2 -s ' + size + ' ' + output_file
        exec_scale = 'ffmpeg -i ' + file + ' -y -s ' + size + ' ' + output_file
        scale.append(exec_scale)
    return(scale)


# 从视频获取声音：输入视频声音目录image\\other；输出aac声音目录：image\\music
def get_audio(output_path):
    info = []
    data = get_files('F:\\image\\other\\','mp4')
    for file in data:
        file_name = os.path.basename(file)
        output_file = output_path + file_name.replace('.mp4','.aac')
        exec_info = 'ffmpeg -i ' + file +' -acodec copy -vn -y ' + output_file
        print(exec_info)
        info.append(exec_info)
    return(info)

# 多个视频进行合并，需要合并的视频格式type，视频输入：F:\\image\\； 视频转换为ts存储的路径
# output_path：合并不同尺寸的视频，以最小尺寸为准
def concat_video(type,output_path,output_video):
    change = ''
    info = get_files('F:\\image\\', type)
    for file in info:
        file_name = os.path.basename(file).replace(type,'ts')
        output_file = output_path + file_name
        exec_change = 'ffmpeg -i ' + file + ' -y -c:a copy -c:v copy -vbsf h264_mp4toannexb ' + output_file
        # 先将视频转换为ts格式
        os.system(exec_change)
        change = change + output_file + '|'
    videos = ('concat:' + change)[:-1]   #  -s 360x640  -s 360x640 -absf aac_adtstoasc
    exec_concat = 'ffmpeg -i "%s" -c:a copy -c:v copy -y ' %(videos) + output_video   # -s 540x960
    # 执行合并视频操作
    print(exec_concat)
    os.system(exec_concat)

# 需要合并的视频格式为ts，视频输入：F:\\image\\ ,output_video视频输出
def concat_ts_video():
    file_path = 'F:\image\\baisui\\06\\'
    ts_path = 'F:\image\\temp\\'
    output_video = 'F:\image\\other\\百岁之好-歌.mp4'
    #rename_num_file(file_path, 'ts', ts_path)
    info = get_files(ts_path, 'ts')
    change = ''
    for file in info:
        print(file)
        change = change + file + '|'
    videos = ('concat:' + change)[:-1]
    exec_concat = 'ffmpeg -i "%s" -c:a copy -c:v copy -y ' % (videos) + output_video  # -s 540x960
    print(exec_concat)
    os.system(exec_concat)


# 需要合并的声音格式type，单个声音目录，合并后声音目录
def concat_audio(type,input_path,output_path):
    change = ''
    info = get_files(input_path, type)
    for file in info:
        file_name = os.path.basename(file).replace(type,'aac')
        output_file = input_path + file_name
        change = change + output_file + '|'
    videos = ('concat:' + change)[:-1]
    exec_concat = 'ffmpeg -i "%s"  -y ' %(videos) + output_path
    # 执行合并声音操作
    print(exec_concat)
    os.system(exec_concat)


# 需要翻转的视频格式type，需要重新编码-c:v libx264，原视频目录：image\\ 新视频目录image\\temp
def rotate_video(type,output_path):
    info = get_files('F:\\image\\', type)
    for file in info:
        file_name = os.path.basename(file)
        output_file = output_path + file_name
        exec_rotate = 'ffmpeg -i %s -metadata:s:v:0 rotate=90 -vf transpose=2 -c:v libx264 -c:a copy -y ' %(file) + output_file
        #print(exec_rotate)
        os.system(exec_rotate)


# 需要截取的视频格式type，原视频目录：image\\ 新视频目录image\\temp
def crop_video(type,output_path,size):
    info = get_files('F:\\image\\', type)
    for file in info:
        file_name = os.path.basename(file)
        output_file = output_path + file_name
        exec_crop = 'ffmpeg -i %s -vf crop=%s' %(file,size) +'-y '+ output_file
        print(exec_crop)
        os.system(exec_crop)


# 视频反转（从后面往前）：1.分解为图片到临时目录；2-图片复制反转命名；3-图片合成视频
def reverse_video(video):
    temp_path = 'F:\image\\temp\\'
    image_path = os.path.dirname(video)+'\\'
    file_name = os.path.basename(video)
    out_video = image_path +file_name.replace('.','_copy.')
    time = math.ceil(float(get_info(video)['streams'][0]['duration']))
    out_name = 'image_%03d'
    get_image(video,temp_path,time,out_name)                # 1.分解为图片到临时目录
    copy_rename_files(temp_path,'jpg',image_path,out_name)
    os.system('ffmpeg -i %s -y -r 25 %s'%(image_path+out_name+'.jpg',out_video))

def exec_system(info):
    os.system(info)

def main(i):
    if i == 1:
        info = scale_info('1280x590', 'F:\image\\other\\')  # 360x640  540x960  960x540  720*720 1280x720 720x1280
    else:
        info = get_audio('F:\image\\music\\')
    threads = []
    for data in info:
        t = threading.Thread(target=exec_system, args=(data,))
        threads.append(t)

    for t in threads:
        t.start()

    for t in threads:
        t.join()



if __name__ == '__main__':
    #main(2)   # 1-压缩视频（更改分辨率）,2-获取音频
    concat_video('mp4','F:\image\\temp\\','F:\image\\new\\automatic3.mp4')   # 合并视频
    #concat_ts_video()
    #main(2)   # 1-压缩视频（更改分辨率）,2-获取音频
    #concat_video('mp4','F:\image\\temp\\','F:\image\\other\\高清-.mp4')   # 合并视频
    #rotate_video('mp4', 'F:\image\\temp\\')
    #crop_video('mp4', 'F:\image\\temp\\','1278.5:540:0.6:27')   # 1278.5:540:0.6:27 ,1051:588.5:114:0.6
    #concat_audio('aac','F:\image\music\\','F:\image\music\\思思.mp3')
    #threading_video_image('F:\image\\temp\\01\\')
    #reverse_video('F:\image\\child\\h.mp4')     # 视频反转
    #get_audio('F:\image\music\\')
